﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pavilion.GameTools;

namespace Pavilion.Locks
{
    public class CharacterInputLockMonitor : LockMonitorBase
    {
        private CharacterInputLock characterInputLock;
        private CharacterInputTool characterInputTool;
        private bool isDisposed;

        public CharacterInputLockMonitor(CharacterInputLock characterInputLock)
        {
            this.characterInputLock = characterInputLock;
        }

        public override void Dispose()
        {
            characterInputTool.PressedInputChanged -= new Action<IEnumerable<CharacterInput>>(CharacterInputTool_PressedInputChanged);
            characterInputTool.ReleasedInputChanged -= new Action<IEnumerable<CharacterInput>>(CharacterInputTool_ReleasedInputChanged);

            characterInputLock = null;
            characterInputTool = null;
            isDisposed = true;
        }

        public override void Load(GameItem gameItem)
        {
            characterInputTool = gameItem.ObtainTool<CharacterInputTool>();

            characterInputTool.PressedInputChanged += new Action<IEnumerable<CharacterInput>>(CharacterInputTool_PressedInputChanged);
            characterInputTool.ReleasedInputChanged += new Action<IEnumerable<CharacterInput>>(CharacterInputTool_ReleasedInputChanged);

            UpdateLock();
        }

        private void UpdateLock()
        {
            if (isDisposed)
                return;

            if (characterInputLock.IsPressed)
                IsOpen = characterInputTool.PressedInput.Contains(characterInputLock.Input);
            else
                IsOpen = characterInputTool.ReleasedInput.Contains(characterInputLock.Input);
        }

        private void CharacterInputTool_PressedInputChanged(IEnumerable<CharacterInput> pressedInput)
        {
            UpdateLock();
        }

        private void CharacterInputTool_ReleasedInputChanged(IEnumerable<CharacterInput> releasedInput)
        {
            UpdateLock();
        }
    }
}
